﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Player : MonoBehaviour
{
    public float smoothing ;
    public float resttime ;
    public float resttimer;
    private Rigidbody2D rig;
    private BoxCollider2D bc;
    private Animator animator;

    private Vector3 targetPostion = new Vector3(1f, 1f,0f);
    
    // Start is called before the first frame update
    void Start()
    {
        rig = GetComponent<Rigidbody2D>();
        bc = GetComponent<BoxCollider2D>();
        animator = GetComponent<Animator>();
        smoothing = 9.5f;
        resttime = 0.5f;
    }


    void FixedUpdate()
    {
        rig.MovePosition(Vector3.Lerp(transform.position, targetPostion, smoothing*Time.fixedDeltaTime));//移动人物
        float h = Input.GetAxisRaw("Horizontal");
        float v = Input.GetAxisRaw("Vertical");
        
        resttimer += Time.deltaTime;
        if (resttimer<resttime)//休息时间不满足就不能移动
        {
            return;
        }
        if (h>0 || h<0)
        {
            v = 0;//限制不能斜着移动

        }
        
        if (h!=0||v!=0)
        {
            bc.enabled = false;
            RaycastHit2D hit = Physics2D.Linecast(transform.position, transform.position + new Vector3(h, v, 0f));
            bc.enabled = true;
            if (hit.transform == null)
            {
                targetPostion += new Vector3(h, v, 0);

            }
            else
            {
                switch (hit.collider.tag)
                {
                    case "OutWall":
                        break;
                    case "Wall":
                        hit.collider.SendMessage("TakeDamage");
                        animator.SetTrigger("Attack");
                        break;
                    case "Soda":
                        targetPostion += new Vector3(h, v, 0);
                        GameManager.Instance.HpAdd(20);
                        Destroy(hit.transform.gameObject);
                        break;
                    case "Food":
                        targetPostion += new Vector3(h, v, 0);
                        GameManager.Instance.HpAdd(10);
                        Destroy(hit.transform.gameObject);
                        break;
                    case "Enemy":
                        break;
                }
            }
            GameManager.Instance.PlayerOnMove();//player移动了，调用这个方法控制敌人移动

            resttimer = 0;
        }
        

        
    }
}
